package heven.holt.wan.android.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.activityViewModels
import androidx.navigation.fragment.findNavController
import dagger.hilt.android.AndroidEntryPoint
import heven.holt.library.base.BaseFragment
import heven.holt.library.extensions.check
import heven.holt.library.loading.LoadingStateView
import heven.holt.library.loading.extensions.setLoadingStateBackWithBackgroundDecorHeader
import heven.holt.wan.android.databinding.FragmentLoginBinding
import heven.holt.wan.android.loading.delegate.BackgroundTitleDecorViewDelegate
import heven.holt.wan.android.viewmodel.LoginParams
import heven.holt.wan.android.viewmodel.UserViewModel

@AndroidEntryPoint
class LoginFragment : BaseFragment<FragmentLoginBinding>() {
    private lateinit var loadingStateView: LoadingStateView

    private val userViewModel: UserViewModel by activityViewModels()

    override fun createDecorationView(): View {
        loadingStateView =
            binding.root.setLoadingStateBackWithBackgroundDecorHeader(
                BackgroundTitleDecorViewDelegate()
            )
        return loadingStateView.decorView
    }

    override fun bindViewBinding(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): FragmentLoginBinding = FragmentLoginBinding.inflate(inflater, container, false)

    override fun initView() {
    }

    override fun initData() {
        binding.handlers = Handlers()
        binding.params = LoginParams()

        userViewModel.loginState.observe(viewLifecycleOwner) { success ->
            if (success)
                findNavController().navigateUp()
        }
    }

    inner class Handlers {
        fun login() {
            val params = binding.params ?: return
            if (params.username.check("用户名不能为空")) return
            if (params.password.check("密码不能为空")) return
            userViewModel.login(params.username, params.password)
        }
    }
}